1

迭代器 - Iterators

{
    'use strict'
    function chef(foods){
        let i = 0;
        return {
            next(){
                let done = (i >= foods.length);
                let value = !done ? foods[i++]:undefined;

                return{
                    value:value,
                    done:done
                }
            }
        }
    }
    let wanghao = chef(['西红柿','孙双双']);
    console.log(wanghao.next());
    console.log(wanghao.next());
    console.log(wanghao.next());
}

结果:
{value: "西红柿", done: false}
{value: "孙双双", done: false}
{value: undefined, done: true}

生成器 - Generators

{
    'use strict'
    function* chef(){
        yield '西红柿';
        yield '炒蛋';
    }
    let wanghao = chef();
    console.log(wanghao.next());
    console.log(wanghao.next());
    console.log(wanghao.next());
}

结果:
{value: "西红柿", done: false}
{value: "孙双双", done: false}
{value: undefined, done: true}

模版字符串 - ``

{
    // 普通字符串
    let str = `In JavaScript '\n' is a line-feed.`;
    console.log(str);
     
    // 多行字符串
    let str2 = `In JavaScript this is
        not legal.`;
    console.log(str2);
     
    // 字符串中嵌入变量
    let name = 'liushi';
    window.location.href = `http://www.baidu.com?name=${name}`;
}

函数的参数默认值

// ES6之前,当未传入参数时,text = 'default';
function printText(text) {
    text = text || 'default';
    console.log(text);
}

// ES6;
function printText(text = 'default') {
    console.log(text);
}

Spread / Rest 操作符

当被用于迭代器中时,它是一个 Spread 操作符:

function foo(x,y,z) {
  console.log(x,y,z);
} 
let arr = [1,2,3];
foo(...arr); // 1 2 3

当被用于函数传参时,是一个 Rest 操作符:当被用于函数传参时,是一个 Rest 操作符:

function foo(...args) {
  console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

for...of 和 for...in

{
    //返回值
    let letters = ['a', 'b', 'c'];
    letters.size = 3;
    for (let letter of letters) {
      console.log(letter);
    }
    // 结果: a, b, c
    
    //返回键,es6
    let stus = ['Sam', '22', '男'];
    stus.size = 3;
    for (let stu in stus) {
      console.log(stu);
    }
    // 结果: 0,1,2,size
}


liuoomei
175 声望18 粉丝

走出舒适区,外面的风景格外迷人!